const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
const port = 3000;

// 数据存储文件路径
const dataFilePath = path.join(__dirname, 'data', 'schedules.json');

// 确保 data 目录存在
const dataDirectory = path.dirname(dataFilePath);
if (!fs.existsSync(dataDirectory)) {
    fs.mkdirSync(dataDirectory, { recursive: true });
}

// 初始化数据文件
if (!fs.existsSync(dataFilePath)) {
    const initialData = [];
    fs.writeFileSync(dataFilePath, JSON.stringify(initialData, null, 2), 'utf8');
    console.log('数据文件已初始化');
}

// 解析 JSON 请求体
app.use(express.json());
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 读取日程数据
function readSchedules() {
    try {
        const data = fs.readFileSync(dataFilePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取日程数据时出错:', error);
        return [];
    }
}

// 写入日程数据
function writeSchedules(schedules) {
    try {
        fs.writeFileSync(dataFilePath, JSON.stringify(schedules, null, 2), 'utf8');
        console.log('日程数据已保存');
    } catch (error) {
        console.error('保存日程数据时出错:', error);
    }
}

// 添加日程
app.post('/add', (req, res) => {
    const { date, time, activity } = req.body;
    const schedules = readSchedules();
    schedules.push({ date, time, activity });
    writeSchedules(schedules);
    res.json({ success: true });
});

// 查询日程
app.get('/query', (req, res) => {
    const date = req.query.date;
    const schedules = readSchedules();
    const filteredSchedules = schedules.filter(schedule => schedule.date === date);
    res.json({ schedules: filteredSchedules });
});

// 删除日程
app.post('/delete', (req, res) => {
    const { date, time, activity } = req.body;
    const schedules = readSchedules();
    const newSchedules = schedules.filter(schedule => !(schedule.date === date && schedule.time === time && schedule.activity === activity));
    writeSchedules(newSchedules);
    res.json({ success: true });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});
